<?php

class SetupController extends AppController {
    
    // define controller name
    var $name = 'Setup';
    
    // define list of models to use 
    var $uses = array('User','Right','Role','Service');
    
    function beforeFilter() { 
        parent::beforeFilter();
        $this->Auth->allow('index');  
    }
    
    function isAuthorized() { 
        return true;
    }
    
    public function index() {
       
        if ($this->request->is('post')) {
           
            $this->clearDatabase();
            $this->createRootRole();
            $this->createRootUser();
         
            $this->redirect($this->Auth->logoutRedirect);
        }
    }
    
    private function createRootRole() {
        
        $role = array(
            'parent_id'     => null,
            'hierarchy'     => '|',
            'name'          => 'Root Administrator',
            'description'   => 'Master account, all rights enabled.'
        );
            
        $this->Role->create();
        $this->Role->save($role);
        
        foreach (Constants::$rights as $id => $properties) {
            $right = array(
                'role_id'   => $this->Role->id,
                'right_id'  => $id
            );

            $this->Right->create();
            $this->Right->save($right);
        }
    }
    
    private function createRootUser() {
        
        $randomPassword = $this->User->getRandomPassword();          
        $user = array(
            'username'          => trim((string)$this->request->data['Setup']['username']),
            'password'          => $this->Auth->password($randomPassword),
            'retype_password'   => $randomPassword,
            'role_id'           => $this->Role->id,
            'full_name'         => 'Root',
            'address'           => '-',
            'phone'             => '-',
            'active'            => 1,
            'responsabilities'  => 'Supervisor of overall activities.',
        );
        
        $this->User->create();
        $result = $this->User->save($user);
        
        if (!$result) {
            $this->Session->setFlash(__('Please correct the mistakes below',true)); 
            $this->redirect(array('controller' => 'setup','action' => 'index'));
        }
    }
    
    private function clearDatabase() {
        
        $this->User->clearTable();
        $this->Right->clearTable();
        $this->Role->clearTable();
        $this->Service->clearTable();
        
        //$this->Groups->clearDbTable();
        //$this->Messages->clearDbTable();
        
    }
    
}

?>
